#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2011/06/06

'''
from StringIO import StringIO
from google.appengine.ext import db
import dateutil.parser
import datetime
import csv
import re
import string
import sys

stdin = sys.stdin
stdout = sys.stdout
reload(sys)
sys.setdefaultencoding('utf-8')
sys.stdin = stdin
sys.stdout = stdout

class UserCommentData(db.Model):
    date = db.StringProperty(required=True, multiline=False)
    commentKind = db.StringProperty(multiline=False)
    comment = db.TextProperty()
    
class UserCommentDetail:
    # udpate database
    def updateComment(self, csvString, kindString, date):
       commentData = UserCommentData(date = date)
       commentData.comment = csvString
       commentData.commentKind = kindString
       commentData.put()

    def outCommentDetailFromDB(self, kind, keyDate, keyWord):
        result = []
        keyDate = re.sub("'", "", str(keyDate))
        keyWord = re.sub("'", "", str(keyWord))
        kind = re.sub("'", "", str(kind))
        dateStr = dateutil.parser.parse(keyDate)
        dateStr = dateStr + datetime.timedelta(7) #一週間前の日付を入れる
        after = dateStr.strftime('%Y%m%d')
        datas = UserCommentData.gql('WHERE date >= :1 AND date <= :2 AND commentKind = :3 ', keyDate, after, kind)
        for data in datas:
            # data.commentはtext形式なのでstrに変換
            comment = str(data.comment)
            keywords = keyWord.split(' ')
            if self.isSearchKeyWord(comment, keywords):
                detail = []
                detail.append(data.date)
                highLiteComment = self.keyWordHighLite(comment, keywords)
                detail.append(highLiteComment)
                result.append(detail)
        
        return result
        
    
    def isSearchKeyWord(self, comment, keywords):
        for keyword in keywords:
            keyword = re.sub('\(', '\(', keyword)
            keyword = re.sub('\)', '\)', keyword)
            if re.search(keyword, comment) == None:
                return False
        return True
    def keyWordHighLite(self, comment, keywords):
        for keyword in keywords:
            searchword = re.sub('\(', '\(', keyword)
            searchword = re.sub('\)', '\)', searchword)
            comment = re.sub(searchword, '<span class="highlight">' + keyword + '</span>', comment)
        comment = re.sub('\n', '<br>', comment)
        return comment

    def deleteComment(self):
        datas = UserCommentData.all()
        for data in datas:
            data.delete()
